package api

import (
	"fmt"
	"gitee.com/ling1314/origin-utility/model"
	"gitee.com/ling1314/origin-utility/modules/service"
	"gitee.com/ling1314/origin-utility/utils"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
	"os"
	"path"
)

type idpOrgApi struct{}

func (api idpOrgApi) GetOrgList(c *gin.Context) {
	r, err := service.IdpOrgService.GetOrgList(GetCurrentUser(c).UserID)
	if err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, r)
}

func (api idpOrgApi) UpdateOrg(c *gin.Context) {
	var argus model.IdpOrg
	if err := c.ShouldBindJSON(&argus); err != nil {
		BadWithError(c, err)
		return
	}
	if err := service.IdpOrgService.UpdateOrg(argus); err != nil {
		BadWithError(c, err)
		return
	}
	Ok204(c)
}

func (api idpOrgApi) SavePoint(c *gin.Context) {
	argus := struct {
		PlanePic string `json:"planePic,omitempty"` // 在哪些图片上
		JsonStr  string `json:"jsonStr,omitempty"`  //渲染哪些标记点
		OrgId    int64  `json:"orgId,string"`
	}{}
	if err := c.ShouldBindJSON(&argus); err != nil {
		BadWithError(c, err)
		return
	}
	if err := service.IdpOrgService.SavePoint(argus.PlanePic, argus.JsonStr, argus.OrgId); err != nil {
		BadWithError(c, err)
		return
	}
	Ok204(c)
}
func (api idpOrgApi) GetPoint(c *gin.Context) {
	argus := struct {
		Id string `uri:"id"`
	}{}
	if err := c.ShouldBindUri(&argus); err != nil {
		BadWithError(c, err)
		return
	}
	var (
		m   model.IdpOrgPoint
		err error
	)
	if m, err = service.IdpOrgService.GetPoint(argus.Id); err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, m)
}

func (api idpOrgApi) SavePlantPic(c *gin.Context) {
	f, err := c.FormFile("pic")
	if err != nil {
		log.Error(err)
		BadWithError(c, err)
	}
	id := utils.GetSoftId()
	dst := "./static/pic/" + fmt.Sprint(id) + path.Ext(f.Filename)
	err = c.SaveUploadedFile(f, dst)
	if err != nil {
		log.Error(err)
		BadWithError(c, err)
	}
	c.String(http.StatusOK, fmt.Sprint(id)+path.Ext(f.Filename))
}

func (api idpOrgApi) SavePlantPic2(c *gin.Context) {
	mf, err := c.MultipartForm()
	f := mf.File["file"][0]
	id := utils.GetSoftId()
	dst := "./static/pic/" + fmt.Sprint(id) + path.Ext(f.Filename)
	err = c.SaveUploadedFile(f, dst)
	if err != nil {
		log.Error(err)
		BadWithError(c, err)
	}
	c.String(http.StatusOK, "static/pic/"+fmt.Sprint(id)+path.Ext(f.Filename))
}

func (api idpOrgApi) GetMapJson(c *gin.Context) {
	argus := struct {
		Code string `uri:"code"`
	}{}
	if err := c.ShouldBindUri(&argus); err != nil {
		BadWithError(c, err)
		return
	}
	bs, err := os.ReadFile("./static/map/" + argus.Code + ".json")
	if err != nil {
		BadWithError(c, err)
		return
	}

	Ok(c, string(bs))
}
